<template>
	<view class="settings-container" :style="containerStyle">

		<!-- 主要内容区域 -->
		<scroll-view class="content-scroll" scroll-y show-scrollbar="false" :style="{ paddingTop: safeDistance + 'px' }"
			refresher-enabled="true" :refresher-triggered="refreshing" @refresherrefresh="onRefresh">
			<!-- 个人信息卡片 -->
			<view class="settings-card">
				<view class="card-header">
					<text class="card-title">👤 个人信息</text>
					<text class="card-desc">查看和管理你的个人资料</text>
				</view>

				<!-- 用户头像和基本信息 -->
				<view class="user-profile" @click="editProfile">
					<view class="avatar-section">
						<view class="avatar-container">
							<image v-if="userInfo.avatar" :src="getAvatarUrl(userInfo.avatar)" class="user-avatar"
								mode="aspectFill"></image>
							<view v-else class="default-avatar">
								<text class="avatar-text">{{ getAvatarText() }}</text>
							</view>
						</view>
					</view>

					<view class="user-basic-info">
						<text class="user-name">{{ userInfo.nickname || '未设置昵称' }}</text>
						<text class="user-phone">📱 {{ userInfo.phone || '未绑定手机号' }}</text>
						<text class="user-email">📧 {{ userInfo.email || '未绑定邮箱' }}</text>
					</view>

					<view class="profile-edit-arrow">
						<text class="edit-arrow">→</text>
					</view>
				</view>

				<!-- 学习统计 -->
				<StudyStats :userStats="userStats" />

			</view>

			<!-- 主题设置卡片 -->
			<view class="settings-card">
				<ThemeSelector @themeChanged="onThemeChanged" />
			</view>

			<!-- 退出登录卡片 -->
			<view class="settings-card">
				<view class="card-header">
					<text class="card-header-title">👋 账户管理</text>
					<text class="card-header-desc">管理你的登录状态</text>
				</view>

				<!-- 退出登录操作 -->
				<view class="logout-action">
					<view class="action-item" @click="logout">
						<text class="action-icon">👋</text>
						<text class="action-text">退出登录</text>
						<text class="action-arrow">→</text>
					</view>
				</view>
			</view>

		</scroll-view>

		<!-- AI助手按钮 -->
		<AiChatButton buttonText="AI助手" />
	</view>
</template>

<script setup lang="ts">
	import { ref, computed, onMounted } from 'vue';
	import { onShow } from '@dcloudio/uni-app';
	import { getThemeStyles } from '@/stores/theme';
	import AiChatButton from '@/components/AiChatButton.vue';
	import { getUserInfoAPI } from '@/services/user';
	import { getExamStatisticsAPI } from '@/services/exam-records';
	import type { UserInfoResult, ExamStatistics } from '@/types';
	import { baseURL } from '@/utils/config';
	import ThemeSelector from './theme-selector.vue';
	import StudyStats from '@/pages/my/components/study-stats.vue';
	import { logoutAPI } from '@/services/login';

	/**
	 * 安全距离（顶部内边距 = 安全区域 + 基础间距）
	 */
	const safeDistance = computed(() => {
		const systemInfo = uni.getSystemInfoSync();
		const safeAreaTop = systemInfo.safeAreaInsets?.top || 0;
		// 基础间距 20px（约等于 40rpx），加上安全区域
		return safeAreaTop + 20;
	});

const getAvatarUrl = (avatar : string) => {
	if (!avatar) return '';
	// 如果已经是完整URL，直接返回
	if (avatar.startsWith('http')) {
		return avatar;
	}
	// 如果是相对路径，拼接baseURL
	return avatar.startsWith('/') ? baseURL + avatar : baseURL + '/' + avatar;
}


	/**
	 * 用户信息数据（使用项目定义的真实字段）
	 */
	const userInfo = ref<UserInfoResult>({
		nickname: '',
		username: '',
		avatar: '',
		phone: '',
		email: ''
	});

	/**
	 * 用户学习统计数据（从考试记录统计获取）
	 */
	const userStats = ref<ExamStatistics>({
		totalCount: 0,      // 总测试次数
		averageScore: 0,    // 平均分数
		bestScore: 0,       // 最高分数
		averageAccuracy: 0  // 平均正确率
	});

	/**
	 * 加载状态
	 */
	const loading = ref(false);

	/**
	 * 下拉刷新状态
	 */
	const refreshing = ref(false);


	/**
	 * 获取头像文字（用户名首字母）
	 */
	const getAvatarText = () => {
		const nickname = userInfo.value.nickname;
		if (nickname && nickname.length > 0) {
			return nickname.charAt(0).toUpperCase();
		}
		return 'U';
	};


	/**
	 * 跳转到个人信息编辑页面
	 */
	const editProfile = () => {
		uni.navigateTo({
			url: '/pages/my/profile-edit'
		});
	};



	/**
	 * 退出登录
	 */
	const logout = () => {
		uni.showModal({
			title: '退出登录',
			content: '确定要退出当前账户吗？',
			showCancel: true,
			success: (res : any) => {
				if (res.confirm) {
					// 用户确认退出
					performLogout();
				}
				// 用户取消，不执行任何操作
			}
		});
	};



	/**
	 * 执行退出登录操作
	 */
	const performLogout = async () => {
		try {
			try {
				//删除后台token（包括access_token和refresh_token）
				await logoutAPI()
			} catch (error) {
				console.warn('后端logout调用失败，继续清理本地数据:', error)
			}

			// 清除本地存储的用户信息
			uni.removeStorageSync('userInfo');
			uni.removeStorageSync('token');
			uni.removeStorageSync('refreshToken');

			// 显示退出成功提示
			uni.showToast({
				title: '已退出登录',
				icon: 'success',
				duration: 1500
			});

			// 延迟跳转到登录页面
			setTimeout(() => {
				uni.reLaunch({
					url: '/pages/login/index'
				});
			}, 1500);
		} catch (error) {
			console.error('退出登录失败:', error);
			uni.showToast({
				title: '退出登录失败',
				icon: 'none',
				duration: 2000
			});
		}
	};
	/**
	 * 主题变更事件处理
	 */
	const onThemeChanged = (theme : string) => {
		// 更新主题样式
		themeStyles.value = getThemeStyles();
		console.log('主题已切换为:', theme);
	};

	// 获取主题样式，使用ref而不是computed以便可以手动更新
	const themeStyles = ref(getThemeStyles());

	// 容器背景样式
	const containerStyle = computed(() => ({
		background: themeStyles.value.bgGradient
	}));

	/**
	 * 加载用户信息
	 */
	const loadUserInfo = async () => {
		try {
			const res = await getUserInfoAPI();
			if (res.data) {
				userInfo.value = res.data;
			}
		} catch (error) {
			console.error('获取用户信息失败:', error);
			uni.showToast({
				title: '获取用户信息失败',
				icon: 'none',
				duration: 2000
			});
		}
	};

	/**
	 * 加载用户统计数据
	 */
	const loadUserStats = async () => {
		try {
			const res = await getExamStatisticsAPI();
			if (res.data) {
				userStats.value = res.data;
			}
		} catch (error) {
			console.error('获取统计数据失败:', error);
			uni.showToast({
				title: '获取统计数据失败',
				icon: 'none',
				duration: 2000
			});
		}
	};

	/**
	 * 加载所有数据
	 */
	const loadAllData = async (isRefresh = false) => {
		if (!isRefresh) {
			loading.value = true;
			uni.showLoading({
				title: '加载中...',
				mask: true
			});
		}

		try {
			// 并行加载用户信息和统计数据
			await Promise.all([
				loadUserInfo(),
				loadUserStats()
			]);

			if (isRefresh) {
				uni.showToast({
					title: '刷新成功',
					icon: 'success',
					duration: 1500
				});
			}
		} catch (error) {
			console.error('数据加载失败:', error);
			if (isRefresh) {
				uni.showToast({
					title: '刷新失败',
					icon: 'none',
					duration: 2000
				});
			}
		} finally {
			if (!isRefresh) {
				loading.value = false;
				uni.hideLoading();
			}
		}
	};

	/**
	 * 下拉刷新处理
	 */
	const onRefresh = async () => {
		refreshing.value = true;
		try {
			await loadAllData(true);
		} finally {
			refreshing.value = false;
		}
	};

	/**
	 * 页面初始化
	 */
	onMounted(() => {
		// 初始化主题样式
		themeStyles.value = getThemeStyles();

		// 加载用户数据
		loadAllData();
	});


	// 页面展示时刷新信息
	onShow(() => {
		loadAllData();
	});
</script>


<style lang="scss" scoped>
	.settings-container {
		height: 100vh;
		display: flex;
		flex-direction: column;
		overflow: hidden;
		transition: background-color 0.3s ease;
	}


	/**
	 * 内容滚动区域
	 */
	.content-scroll {
		flex: 1;
		padding: 24rpx 24rpx 0;
		width: 100%;
		box-sizing: border-box;
		overflow-y: auto;
		height: 0;
	}

	/**
	 * 设置卡片
	 */
	.settings-card {
		margin-bottom: 32rpx;
		background: v-bind('themeStyles.bgCard');
		border: 1rpx solid v-bind('themeStyles.borderLight');
		border-radius: 24rpx;
		padding: 32rpx;
		box-shadow: v-bind('themeStyles.cardBoxShadow');
	}

	.card-header {
		margin-bottom: 32rpx;
	}

	.card-title {
		font-size: 48rpx;
		font-weight: 900;
		color: v-bind('themeStyles.textPrimary');
		display: block;
		margin-bottom: 8rpx;
		/* 使用主题渐变 */
		background: v-bind('themeStyles.primaryGradient');
		-webkit-background-clip: text;
		-webkit-text-fill-color: transparent;
		background-clip: text;
	}

	.card-desc {
		font-size: 26rpx;
		color: v-bind('themeStyles.textSecondary');
	}

	.card-header-title {
		font-size: 36rpx;
		font-weight: 700;
		color: v-bind('themeStyles.textPrimary');
		display: block;
		margin-bottom: 8rpx;
	}

	.card-header-desc {
		font-size: 26rpx;
		color: v-bind('themeStyles.textSecondary');
	}

	/**
	 * 个人信息相关样式
	 */
	.user-profile {
		display: flex;
		align-items: center;
		gap: 24rpx;
		margin-bottom: 32rpx;
		padding: 24rpx;
		background: v-bind('themeStyles.bgSecondary');
		border-radius: 16rpx;
		border: 1rpx solid v-bind('themeStyles.borderLight');
		cursor: pointer;
		transition: all 0.3s ease;

		&:active {
			transform: scale(0.98);
			background: v-bind('themeStyles.bgHover');
		}
	}

	.profile-edit-arrow {
		margin-left: auto;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 48rpx;
		height: 48rpx;
		border-radius: 50%;
		background: rgba(0, 0, 0, 0.05);

		.edit-arrow {
			font-size: 24rpx;
			color: v-bind('themeStyles.textSecondary');
			font-weight: 600;
		}
	}

	.avatar-section {
		flex-shrink: 0;
	}

	.avatar-container {
		position: relative;
		width: 120rpx;
		height: 120rpx;
		border-radius: 50%;
		overflow: hidden;
		cursor: pointer;
		transition: all 0.3s ease;

		&:active {
			transform: scale(0.95);
		}
	}

	.user-avatar {
		width: 100%;
		height: 100%;
		border-radius: 50%;
	}

	.default-avatar {
		width: 100%;
		height: 100%;
		background: v-bind('themeStyles.primaryGradient');
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
	}

	.avatar-text {
		font-size: 48rpx;
		font-weight: 700;
		color: white;
	}

	.avatar-edit-overlay {
		position: absolute;
		bottom: 0;
		right: 0;
		width: 36rpx;
		height: 36rpx;
		background: v-bind('themeStyles.bgCard');
		border: 2rpx solid v-bind('themeStyles.borderLight');
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: v-bind('themeStyles.cardBoxShadow');
	}

	.edit-icon {
		font-size: 16rpx;
	}

	.user-basic-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.user-name {
		font-size: 32rpx;
		font-weight: 600;
		color: v-bind('themeStyles.textPrimary');
	}

	.user-phone {
		font-size: 24rpx;
		color: v-bind('themeStyles.textSecondary');
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	.user-email {
		font-size: 24rpx;
		color: v-bind('themeStyles.textSecondary');
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	/**
	 * 个人信息操作样式
	 */
	.profile-actions {
		display: flex;
		flex-direction: column;
		gap: 12rpx;
	}

	/**
	 * 退出登录操作样式
	 */
	.logout-action {
		display: flex;
		flex-direction: column;
		gap: 12rpx;
	}

	.action-item {
		display: flex;
		align-items: center;
		gap: 16rpx;
		padding: 20rpx 24rpx;
		background: v-bind('themeStyles.bgSecondary');
		border: 1rpx solid v-bind('themeStyles.borderLight');
		border-radius: 12rpx;
		cursor: pointer;
		transition: all 0.3s ease;

		&:active {
			transform: scale(0.98);
			background: v-bind('themeStyles.bgTertiary');
		}
	}

	.action-icon {
		font-size: 32rpx;
		width: 40rpx;
		text-align: center;
	}

	.action-text {
		flex: 1;
		font-size: 28rpx;
		font-weight: 500;
		color: v-bind('themeStyles.textPrimary');
	}

	.action-arrow {
		font-size: 24rpx;
		color: v-bind('themeStyles.textTertiary');
		font-weight: 600;
	}

	/**
	 * 当前主题显示
	 */
	.current-theme-display {
		display: flex;
		align-items: center;
		gap: 24rpx;
		padding: 24rpx;
		background: v-bind('themeStyles.bgSecondary');
		border: 2rpx solid v-bind('themeStyles.borderLight');
		border-radius: 16rpx;
		transition: all 0.3s ease;
		cursor: pointer;

		&:active {
			transform: scale(0.98);
			background: v-bind('themeStyles.bgTertiary');
		}
	}

	.theme-preview-large {
		width: 100rpx;
		height: 100rpx;
		border-radius: 20rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: v-bind('themeStyles.cardBoxShadow');
		flex-shrink: 0;
		background: v-bind('themeStyles.bgSecondary');
	}

	.preview-dot-large {
		font-size: 50rpx;
		filter: drop-shadow(0 2rpx 6rpx rgba(0, 0, 0, 0.2));
	}

	.current-theme-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.current-theme-name {
		font-size: 32rpx;
		font-weight: 600;
		color: v-bind('themeStyles.textPrimary');
	}

	.current-theme-desc {
		font-size: 24rpx;
		color: v-bind('themeStyles.textSecondary');
	}

	.arrow-right {
		width: 48rpx;
		height: 48rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
	}

	.arrow-icon {
		font-size: 32rpx;
		color: v-bind('themeStyles.textTertiary');
		font-weight: 600;
		transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);

		&.rotate {
			transform: rotate(90deg);
		}
	}

	/**
	 * 风格选择器
	 */
	.style-chooser {
		margin-top: 16rpx;
		padding: 24rpx;
		background: v-bind('themeStyles.bgSecondary');
		border-radius: 20rpx;
		display: grid;
		grid-template-columns: repeat(3, 1fr);
		gap: 20rpx 16rpx;
		animation: slideDown 0.3s cubic-bezier(0.4, 0, 0.2, 1);

		.style-option {
			display: flex;
			flex-direction: column;
			align-items: center;
			gap: 12rpx;
			padding: 20rpx;
			background: v-bind('themeStyles.bgCard');
			border-radius: 16rpx;
			border: 2rpx solid v-bind('themeStyles.borderLight');
			transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
			position: relative;

			&.active {
				border-color: v-bind('themeStyles.primaryColor');
				box-shadow: v-bind('themeStyles.activeShadow');
				transform: scale(1.02);
			}

			&:active {
				transform: scale(0.98);
			}

			.style-preview {
				width: 100%;
				height: 80rpx;
				border-radius: 12rpx;
				box-shadow: v-bind('themeStyles.cardBoxShadow');
			}

			.style-name {
				font-size: 24rpx;
				color: v-bind('themeStyles.textSecondary');
				font-weight: 600;
			}

			.check-icon {
				position: absolute;
				top: 8rpx;
				right: 8rpx;
				width: 32rpx;
				height: 32rpx;
				background: v-bind('themeStyles.primaryColor');
				color: white;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 18rpx;
				font-weight: bold;
			}
		}
	}

	/* 动画定义 */
	@keyframes slideDown {
		from {
			opacity: 0;
			transform: translateY(-10rpx);
		}

		to {
			opacity: 1;
			transform: translateY(0);
		}
	}

	/**
	 * 隐藏滚动条
	 */
	.content-scroll::-webkit-scrollbar {
		display: none;
		width: 0;
		height: 0;
	}
</style>